from rest_framework import viewsets, generics
from rest_framework.decorators import action
from plugin.models import PluginInstallRecord
from plugin.services import plugin_service
from plugin.serializers import PluginInstallRecordSerializer
from libs.simple_responses import api_success
from libs.decorators import required_data_fields


class PluginViewSet(viewsets.GenericViewSet, generics.ListAPIView):
    queryset = PluginInstallRecord.objects.all()
    serializer_class = PluginInstallRecordSerializer
    ordering_fields = ('id',)

    @required_data_fields(['source_app'])
    @action(methods=['post'], detail=False, url_path='set-source-app')
    def set_source_app(self, request, *args, **kwargs):
        source_app = request.data['source_app']
        plugin_service.set_source_app(source_app)
        return api_success({})

    @action(methods=['get'], detail=False, url_path='source-app')
    def get_source_app(self, request, *args, **kwargs):
        source_app = plugin_service.get_source_app()
        return api_success({'source_app': source_app})

    def list(self, request, *args, **kwargs):
        data = plugin_service.get_plugins(request)
        return api_success(data)

    @required_data_fields(['key', 'git_url', 'name'])
    @action(methods=['post'], detail=False)
    def install(self, request, *args, **kwargs):
        plugin_service.install(request.data['key'], request.data['git_url'], request.data['name'])
        return api_success({})

    @required_data_fields(['key'])
    @action(methods=['post'], detail=False)
    def uninstall(self, request, *args, **kwargs):
        plugin_service.uninstall(request.data['key'])
        return api_success({})
